import {Button, Card, Col, DatePicker, Form, Input, InputNumber, message, Modal, Row, Spin, Table, Tooltip} from "antd";
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import FilterForm from "@/components/BaseForm/FilterForm";
import witty from "@/utils/wittyUtils";
import {connect} from "dva";
import TextArea from "antd/es/input/TextArea";

const FormItem = Form.Item;
const {RangePicker} = DatePicker;

let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({insuranceModel}) => ({
    insuranceModel
}))
class AdminInsurance extends React.Component {
    state = {
        //-- 页面数据
        dataSource: [],
        //-- 加载层
        loading: false,
        //-- [true]: 显示搜索条件, [false]: 隐藏搜索条件
        showMoreSearchForm: false,
        //-- 选中的RowKeys
        selectedRowKeys: [],
        //-- 选中的Rows
        selectedRows: [],
        //-- 新增保险编辑模态框
        showInsuranceModal: false
    }

    componentDidMount() {
        //-- 获取表格数据
        this.findPageData();
    }

    /**
     * 查询页面数据
     */
    findPageData = function (params = {}) {
        const thisCtx = this;
        const {dispatch} = this.props;

        if (params.createTime) {
            params.startDate = params.createTime[0].format('YYYY-MM-DD');
            params.endDate = params.createTime[1].format('YYYY-MM-DD');
            delete params.createTime;
        }

        params.currentPage = pagingData._current;
        params.pageSize = pagingData._pageSize;
        console.log(params);
        thisCtx.setState({loading: true});
        dispatch({
            type: 'insuranceModel/policyListPage',
            payload: params,
            callback: function (data) {
                thisCtx.setState({loading: false});
                if (data && data.success) {
                    const paging = data.datas.pagination;
                    pagingData._current = paging.current + 1;
                    pagingData._pageSize = paging.pageSize;
                    pagingData._total = paging.total;
                    thisCtx.setState({
                        //-- 重置选中的行
                        selectedRowKeys: [],
                        selectedRows: [],
                        dataSource: data.datas.list,
                    });
                } else {
                    message.error('保单信息获取失败');
                }
            }
        });
    }

    handlerModal = (type) => {
        let flag = this.state[type];
        this.setState({
            [type]: !flag
        });
        this.props.form.resetFields();
    }

    handlerInsertInsurance = () => {
        const thisCtx = this;
        const {dispatch} = this.props;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (err) return
            if (values.limitDate) {
                values.startDate = values.limitDate[0].format('YYYY-MM-DD');
                values.endDate = values.limitDate[1].format('YYYY-MM-DD');
                delete values.limitDate;
            }
            witty.validNilParams(values);
            console.log(values);
            this.setState({loading: true})
            dispatch({
                type: 'elevatorModel/elevatorInfoListEdit',
                payload: values,
                callback: function (data) {
                    thisCtx.setState({loading: false});
                    if (data && data.success) {
                        message.success('保险新增成功');
                        thisCtx.handlerModal('showInsuranceModal');
                        thisCtx.findPageData();
                    } else {
                        message.error('保险新增失败');
                    }
                }
            });
        })
    }

    handleFilter = (params) => {
        this.params = params;
        witty.validNilParams(params)
        if (witty.isValidObj(params)) {
            pagingData._current = 1;
            witty.validNilParams(params);
            this.findPageData(params);
        }
    }

    formList = [
        {
            type: 'INPUT',
            label: '设备代码',
            field: 'elevatorCode',
        },
        {
            type: 'SELECT',
            label: '保单状态',
            field: 'xstatus',
            list: [{id: 0, name: '未知'}, {id: 1, name: '保障中'}, {id: 2, name: '已过期'}]
        },
        {
            type: 'RANGEPICKER',
            label: '创建时间',
            field: 'createTime',
        },
    ]

    render() {

        const {showInsuranceModal, loading, selectedRowKeys, dataSource} = this.state;
        const {getFieldDecorator} = this.props.form;

        const formLayout = {
            layout: 'vertical',
            labelCol: {
                xs: 24,
                sm: 24
            },
            wrapperCol: {
                xs: 24,
                sm: 24
            }
        }

        const formItemLayout = {
            style: {
                margin: '0px',
            },
        }

        const colLayout = {
            span: 12,
        }

        const rowLayout = {
            gutter: 18,
        }

        const buttonsStyle = {
            style: {
                marginRight: '15px',
            },
        };

        /**
         * 表格选中事件
         */
        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys: selectedRowKeys,
                    selectedRows: selectedRows,
                });
            },
        };

        return (
            <div>
                <Spin spinning={loading}>
                    <PageHeaderWrapper>
                        <Card style={{width: '100%', marginTop: '10px'}}>
                            <FilterForm formList={this.formList} filterSubmit={this.handleFilter}/>
                        </Card>

                        <Card style={{width: '100%', marginTop: '10px'}}>
                            <Tooltip title={'导入投保数据'}>
                                <Button
                                    icon="import"
                                    type="primary"
                                    {...buttonsStyle}
                                    onClick={() => message.info('导入功能还未实现,敬请期待')}
                                >
                                    导入
                                </Button>
                            </Tooltip>
                            <Tooltip title={'新增投保数据'}>
                                <Button
                                    icon="plus"
                                    type="primary"
                                    {...buttonsStyle}
                                    onClick={() => this.handlerModal('showInsuranceModal')}
                                >
                                    新增
                                </Button>
                            </Tooltip>
                        </Card>

                        <Card style={{width: '100%', marginTop: '10px', overflow: "auto"}}>
                            <Table
                                bordered
                                rowKey={data => `${data.id}`}
                                rowSelection={rowSelection}
                                columns={this.columns}
                                dataSource={dataSource}
                                pagination={{
                                    pageSize: pagingData._pageSize,
                                    current: pagingData._current,
                                    total: pagingData._total,
                                    onChange: (page) => {
                                        pagingData._current = page;
                                        this.findPageData();
                                    },
                                    showTotal: total => `共 ${total} 条数据`,
                                    style: {
                                        float: "left"
                                    }
                                }}
                            />
                        </Card>
                        <Modal
                            footer={false}
                            visible={showInsuranceModal}
                            width={650}
                            onCancel={() => this.handlerModal('showInsuranceModal')}
                        >
                            <Form {...formLayout}>
                                <Row {...rowLayout}>
                                    <Col {...colLayout}>
                                        <FormItem {...formItemLayout} label={'使用单位名称'} key={'uorgName'}>
                                            {
                                                getFieldDecorator('uorgName', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            whitespace: true,
                                                            message: '请输入单位名称'
                                                        }
                                                    ]
                                                })(
                                                    <Input type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col {...colLayout}>
                                        <FormItem label={
                                            <span>电梯所在位置
                                                <em style={{
                                                    color: 'gray',
                                                    fontStyle: 'normal'
                                                }}>(使用地址)</em>
                                            </span>
                                        } key={'location'}>
                                            {
                                                getFieldDecorator('location', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            whitespace: true,
                                                            message: '请输入电梯所在位置(使用地址)'
                                                        }
                                                    ]
                                                })(
                                                    <Input type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col {...colLayout}>
                                        <FormItem label={'统一社会信用代码'} key={'ocode'}>
                                            {
                                                getFieldDecorator('ocode', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请输入统一社会信用代码'
                                                        },
                                                        {
                                                            pattern: /[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/g,
                                                            message: '请输入正确的统一社会信用代码'
                                                        }
                                                    ]
                                                })(
                                                    <Input type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col {...colLayout}>
                                        <FormItem label={'设备代码'} key={'elevatorCode'}>
                                            {
                                                getFieldDecorator('elevatorCode', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            whitespace: true,
                                                            message: '请输入设备代码'
                                                        }
                                                    ]
                                                })(
                                                    <Input type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col {...colLayout}>
                                        <FormItem label={'设备型号/使用编号'} key={'useNum'}>
                                            {
                                                getFieldDecorator('useNum', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            whitespace: true,
                                                            message: '请输入设备型号/使用编号'
                                                        }
                                                    ]
                                                })(
                                                    <Input type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col {...colLayout}>
                                        <FormItem label={'维保单位'} key={'maintenance'}>
                                            {
                                                getFieldDecorator('maintenance', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            whitespace: true,
                                                            message: '请输入维保单位'
                                                        }
                                                    ]
                                                })(
                                                    <Input type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col  {...colLayout}>
                                        <FormItem label={'保障期限'} key={'limitDate'}>
                                            {
                                                getFieldDecorator('limitDate', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请选中保障期限'
                                                        }
                                                    ]
                                                })(
                                                    <RangePicker showTime={true} format={'YYYY-MM-DD'}
                                                                 style={{width: '100%'}}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col {...colLayout}>
                                        <FormItem label={
                                            <span>原保费
                                                <em style={{
                                                    color: 'gray',
                                                    fontStyle: 'normal'
                                                }}>(元)</em>
                                            </span>
                                        } key={'price'}>
                                            {
                                                getFieldDecorator('price', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请输入原保费'
                                                        }
                                                    ]
                                                })(
                                                    <InputNumber style={{width: '100%'}} type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col {...colLayout}>
                                        <FormItem label={'备注'} key={'remark'}>
                                            {
                                                getFieldDecorator('remark', {})(
                                                    <TextArea allowClear={true} autoSize={{maxRows: 3, minRows: 3}}
                                                              type={'primary'}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                    <Col span={24} style={{textAlign: 'center', height: '32px', lineHeight: '32px'}}>
                                        <FormItem wrapperCol={{xs: 24, sm: 24, md: 24, lg: 24}}>
                                            <Button type={'primary'} style={{margin: '0 20px'}}
                                                    onClick={() => this.handlerInsertInsurance()}>保存</Button>
                                            <Button onClick={() => this.handlerModal('showInsuranceModal')}>取消</Button>
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </Modal>
                    </PageHeaderWrapper>
                </Spin>
            </div>
        );
    }

    /**
     * 表格列
     */
    columns = [
        {
            title: '使用单位名称',
            align: 'center',
            dataIndex: 'uorgName',
            key: 'uorgName',
        },
        {
            title: '使用地址',
            align: 'center',
            dataIndex: 'location',
            key: 'location',
        },
        {
            title: '上传时间',
            align: 'center',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '设备代码',
            align: 'center',
            dataIndex: 'elevatorCode',
            key: 'elevatorCode',
        },
        {
            title: '维保单位',
            align: 'center',
            dataIndex: 'maintenance',
            key: 'maintenance',
        },
        {
            title: '保障期限',
            align: 'center',
            dataIndex: 'limitDate',
            key: 'limitDate',
        },
        {
            title: '保单状态',
            align: 'center',
            dataIndex: 'xstatusName',
            key: 'xstatusName',
        },
        {
            title: '保费',
            align: 'center',
            dataIndex: 'price',
            key: 'price',
        },
    ]
}

export default Form.create()(AdminInsurance);
